<?php

namespace addon\lian\model\sqlmodel;

use addon\lian\model\LianLevel;
use addon\lian\model\sqlmodel\MemberModel;
use addon\lian\model\sqlmodel\LianLevelModel;
use think\facade\Log;
use think\Model;
use think\facade\Db;

/**
 * 链动2+1会员模型 - 支持ThinkPHP模型关联
 */
class LianMemberModel extends Model
{
    protected $name = 'lian_member';
    protected $pk = 'id';

    /**
     * 关联会员信息
     * @return \think\model\relation\BelongsTo
     */
    public function member()
    {
        return $this->belongsTo(MemberModel::class, 'member_id', 'member_id');
    }

    /**
     * 关联直推上级会员信息
     * @return \think\model\relation\BelongsTo
     */
    public function parentMember()
    {
        return $this->belongsTo(MemberModel::class, 'pid', 'member_id');
    }

    /**
     * 关联链动上级会员信息
     * @return \think\model\relation\BelongsTo
     */
    public function lianParentMember()
    {
        return $this->belongsTo(MemberModel::class, 'lian_pid', 'member_id');
    }

    /**
     * 关联链动等级信息
     * @return \think\model\relation\BelongsTo
     */
    public function lianLevel()
    {
        return $this->belongsTo(LianLevelModel::class, 'level_id', 'level_id');
    }

    /**
     * 关联链动等级信息 (别名)
     * @return \think\model\relation\BelongsTo
     */
    public function level()
    {
        return $this->belongsTo(LianLevelModel::class, 'level_id', 'level_id');
    }

    /**
     * 关联直推下级1会员信息
     * @return \think\model\relation\BelongsTo
     */
    public function child1Member()
    {
        return $this->belongsTo(MemberModel::class, 'child_mid1', 'member_id');
    }

    /**
     * 关联直推下级2会员信息
     * @return \think\model\relation\BelongsTo
     */
    public function child2Member()
    {
        return $this->belongsTo(MemberModel::class, 'child_mid2', 'member_id');
    }

    /**
     * 关联所有直推下级（一对多）
     * @return \think\model\relation\HasMany
     */
    public function children()
    {
        return $this->hasMany('addon\lian\model\sqlmodel\LianMemberModel', 'pid', 'member_id');
    }

    /**
     * 关联链动奖励记录（一对多）
     * @return \think\model\relation\HasMany
     */
    public function rewards()
    {
        return $this->hasMany('addon\lian\model\LianReward', 'member_id', 'member_id');
    }

    /**
     * 使用模型关联获取链动会员分页列表
     * @param array $condition
     * @param int $page
     * @param int $page_size
     * @param string $order
     * @param string $nickname 会员昵称搜索
     * @param string $mobile 会员手机号搜索
     * @return array
     */
    public function getLianMemberPageListWithRelation($condition = [], $page = 1, $page_size = 15, $order = 'create_time desc', $nickname = '', $mobile = '')
    {
        try {
            // 构建查询条件
            $query = $this->where($condition);

            // 处理会员昵称搜索（关联表查询）
            if (!empty($nickname)) {
                $query->whereHas('member', function($query) use ($nickname) {
                    $query->where('nickname', 'like', '%' . $nickname . '%');
                });
            }

            // 处理会员手机号搜索（关联表查询）
            if (!empty($mobile)) {
                $query->whereHas('member', function($query) use ($mobile) {
                    $query->where('mobile', 'like', '%' . $mobile . '%');
                });
            }
            
            // 预载入关联数据
            $query->with([
                'member' => function($query) {
                    $query->field('member_id,nickname,headimg,mobile,username');
                },
                'parentMember' => function($query) {
                    $query->field('member_id,nickname,headimg');
                },
                'lianParentMember' => function($query) {
                    $query->field('member_id,nickname,headimg');
                },
                'level' => function($query) {
                    $query->field('level_id,level_name');
                },
                'child1Member' => function($query) {
                    $query->field('member_id');
                },
                'child2Member' => function($query) {
                    $query->field('member_id');
                }
            ]);

            // 分页查询
            $list = $query->order($order)->paginate([
                'list_rows' => $page_size,
                'page' => $page
            ]);

            // 格式化数据
            $result = [];
            foreach ($list->items() as $item) {
                $data = $item->toArray();
                
                // 格式化金额
                $data['commission'] = number_format($data['commission'] ?? 0, 2);
                $data['give_commission'] = number_format($data['give_commission'] ?? 0, 2);
                $data['frozen_commission'] = number_format($data['frozen_commission'] ?? 0, 2);
                
                // 处理关联数据
                $data['pid_info'] = $data['parent_member'] ?? null;
                $data['lian_pid_info'] = $data['lian_parent_member'] ?? null;
                $data['level_name'] = (isset($data['level']) && $data['level']) ? ($data['level']['level_name'] ?? '未设置') : '未设置';
                $data['child_mid1_exists'] = (isset($data['child1_member']) && $data['child1_member']) ? ($data['child1_member']['member_id'] ?? 0) : 0;
                $data['child_mid2_exists'] = (isset($data['child2_member']) && $data['child2_member']) ? ($data['child2_member']['member_id'] ?? 0) : 0;
                
                // 会员基础信息
                if (isset($data['member']) && $data['member']) {
                    $data['nickname'] = $data['member']['nickname'] ?? '';
                    $data['headimg'] = $data['member']['headimg'] ?? '';
                    $data['member_mobile'] = $data['member']['mobile'] ?? '';
                    $data['username'] = $data['member']['username'] ?? '';
                } else {
                    // 如果没有关联会员信息，设置默认值
                    $data['nickname'] = '';
                    $data['headimg'] = '';
                    $data['member_mobile'] = '';
                    $data['username'] = '';
                }
                
                $result[] = $data;
            }

            return [
                'code' => 0,
                'message' => 'SUCCESS',
                'data' => [
                    'count' => $list->total(),
                    'list' => $result,
                    'page' => $page,
                    'page_size' => $page_size
                ]
            ];

        } catch (\Exception $e) {
            Log::error('查询链动会员失败: ' . $e->getMessage());
            return [
                'code' => -1,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 根据会员ID获取链动会员信息（带关联）
     * @param int $member_id
     * @return array
     */
    public function getLianMemberWithRelation($member_id)
    {
        try {
            $data = $this->with([
                'member',
                'parentMember',
                'lianParentMember',
                'level',
                'child1Member',
                'child2Member'
            ])->where('member_id', $member_id)->find();

            if (!$data) {
                return [
                    'code' => -1,
                    'message' => '链动会员不存在',
                    'data' => null
                ];
            }

            return [
                'code' => 0,
                'message' => 'SUCCESS',
                'data' => $data->toArray()
            ];

        } catch (\Exception $e) {
            return [
                'code' => -1,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => null
            ];
        }
    }

    /**
     * 获取会员的直推下级列表
     * @param int $member_id
     * @param int $limit
     * @return array
     */
    public function getDirectChildren($member_id, $limit = 10)
    {
        try {
            $children = $this->with(['member'])
                ->where('pid', $member_id)
                ->limit($limit)
                ->select();

            return [
                'code' => 0,
                'message' => 'SUCCESS',
                'data' => $children->toArray()
            ];

        } catch (\Exception $e) {
            return [
                'code' => -1,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ];
        }
    }

    /**
     * 获取会员的链动下级列表
     * @param int $member_id
     * @param int $limit
     * @return array
     */
    public function getLianChildren($member_id, $limit = 10)
    {
        try {
            $children = $this->with(['member'])
                ->where('lian_pid', $member_id)
                ->limit($limit)
                ->select();

            return [
                'code' => 0,
                'message' => 'SUCCESS',
                'data' => $children->toArray()
            ];

        } catch (\Exception $e) {
            return [
                'code' => -1,
                'message' => '查询失败: ' . $e->getMessage(),
                'data' => []
            ];
        }
    }
}
